<template>
  <div class="container">
    <TopSearch
      :value="formData"
      :approval-options="approvalOptions"
      :ship-options="shipOptions"
      :money-back-options="moneyBackOptions"
      @submitData="submitData"
    />
    <el-card style="margin-top: 12px;">
      <BaseTable
        ref="applicationForm"
        :table-data="tableData"
        :total="total"
        :loading="tableDataLoading"
        show-index
        show-pagination
        @pagination="handlePagination"
      >
        <el-table-column
          label="发货申请编号"
          prop="applyNo"
          width="150px"
          show-overflow-tooltip
        >
          <template slot-scope="{row}">
            <span v-if="hasPermission(roles, 'f01_01')" class="shopNameLink" @click="toDetail(row)">{{ row.applyNo }}</span>
            <span v-else>{{ row.applyNo }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="所属订单"
          prop="orderNo"
          show-overflow-tooltip
        />

        <el-table-column
          label="所属PI"
          prop="piNo"
          show-overflow-tooltip
        />

        <el-table-column
          label="客户"
          prop="companyNameForeign"
          show-overflow-tooltip
        >
          <template slot-scope="{row}">
            <span v-if="hasPermission(roles, 'f04_01')" class="shopNameLink" @click="toCustomerDetail(row)">{{ row.companyNameForeign }}</span>
            <span v-else>{{ row.companyNameForeign }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="国家"
          prop="countryCode"
          show-overflow-tooltip
        >
          <template slot-scope="{row}">
            <span>{{ getLabelForStatus('countryOptions', row.countryCode) }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="申请总额"
          prop="deliveryApplyAmount"
          show-overflow-tooltip
        >
          <template slot-scope="{row}">
            <span>{{ `${row.currencyCode} ${formatMoneyAmount(row.deliveryApplyAmount)}` }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="审批状态"
          prop="approveStatus"
          show-overflow-tooltip
        >
          <template slot-scope="{row}">
            <span>{{ getLabelForStatus('approvalOptions', row.approveStatus) }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="发货状态"
          prop="deliverStatus"
          show-overflow-tooltip
        >
          <template slot-scope="{row}">
            <span>{{ getLabelForStatus('shipOptions', row.deliverStatus) }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="回款状态"
          prop="paymentStatus"
          show-overflow-tooltip
        >
          <template slot-scope="{row}">
            <span>{{ getLabelForStatus('moneyBackOptions', row.paymentStatus) }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="申请人"
          prop="applyUser"
          show-overflow-tooltip
        >
          <template slot-scope="{row}">
            <span>{{ formatUserName(row.applyUser) }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="申请时间"
          prop="applyTime"
          width="134px"
          show-overflow-tooltip
        >
          <template slot-scope="{row}">
            <span>{{ formatTime(row.applyTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="当前审批人"
          prop="currentApproveUserList"
          width="134px"
          show-overflow-tooltip
        >
          <template slot-scope="{row}">
            <span>{{ formatArrayToStr(geneateAccountOrNameList(row.currentApproveUserList).nameList) }}</span>
          </template>
        </el-table-column>

        <el-table-column
          fixed="right"
          label="操作"
          width="100px"
        >
          <template v-slot="scope">
            <el-button
              v-if="+scope.row.approveStatus=== 0 && isCurrentApproval(scope.row.currentApproveUserList, userAccount)"
              v-permission="['f01_02']"
              type="text"
              @click="agree(scope.row)"
            >审批</el-button>
            <el-button
              v-if="+scope.row.approveStatus=== 0 && isCurrentApproval(scope.row.currentApproveUserList, userAccount)"
              v-permission="['f01_03']"
              type="text"
              @click="reject(scope.row)"
            >驳回</el-button>
          </template>
        </el-table-column>
      </BaseTable>
    </el-card>
    <AgreeOrReject
      :title="title"
      :submit-loading="submitLoading"
      :visible="visible"
      :data="data"
      :is-agree="isAgree"
      @close="visible = false"
      @submit="handleSubmit"
    />
  </div>
</template>

<script>
import TopSearch from './components/TopSearch'
import BaseTable from '@/components/BaseTable'
import AgreeOrReject from './components/AgreeOrReject'
import { formatTime } from '@/utils/tools'
import { getDeliveryApplyList, updateAgree, updateFail } from '@/service/ship'
import { Title } from './baseData'
import {
  formatUserName,
  formatMoneyAmount,
  geneateAccountOrNameList,
  formatArrayToStr,
  hasPermission
} from '@/utils/tools'
import { mapGetters } from 'vuex'

export default {
  name: 'ApplicationForm',
  components: {
    TopSearch,
    BaseTable,
    AgreeOrReject
  },
  data() {
    return {
      approvalOptions: [], // 审批状态
      submitLoading: false,
      tableDataLoading: false,
      shipOptions: [], // 发货状态
      moneyBackOptions: [], // 回款状态
      countryOptions: [], // 国家
      tableData: [],
      tableLoading: false,
      formData: {
        applyNo: '', // 发货申请编号
        companyNameForeign: '', // 客户名称
        applyUser: '', // 申请人名称
        applyDate: [], // 申请日期
        approveStatus: '0', // 审批状态
        deliverStatus: '', // 发货状态
        paymentStatus: '' // 回款状态
      },
      pageIndex: 1,
      pageSize: 10,
      total: 0,
      visible: false,
      title: '',
      data: {},
      isAgree: false
    }
  },
  computed: {
    ...mapGetters(['roles']),
    userAccount() {
      return this.$store.state?.global?.user?.account || this.$store.state.user.account
    }
  },
  beforeMount() {
    this.initBaseData('approve_status', 'approvalOptions') // 审批状态
    this.initBaseData('deliver_status', 'shipOptions') // 发货状态
    this.initBaseData('payment_status', 'moneyBackOptions') // 发货状态
    this.initBaseData('country_code', 'countryOptions') // 国家
  },
  mounted() {
    this.requestData()
  },
  beforeRouteEnter(to, from, next) {
    // 如果从详情过来，将list的isBack设置为true
    if (from.name === 'shipDetail') {
      to.meta.isBack = true
    }
    next()
  },
  activated: function() {
    if (this.$route.meta.isBack) {
      // 请求数据
      this.requestData()
    }
    // 重新设置当前路由的isBack
    this.$route.meta.isBack = false
  },
  methods: {
    hasPermission,
    formatMoneyAmount,
    formatUserName,
    formatTime,
    geneateAccountOrNameList,
    formatArrayToStr,
    requestData() {
      this.tableDataLoading = true
      const { applyDate, ...rest } = this.formData
      const [startDate, endDate] = applyDate || []
      const params = {
        ...rest,
        pageNum: this.pageIndex,
        pageSize: this.pageSize,
        applyStartDate: startDate && `${startDate} 00:00:00`,
        applyEndDate: endDate && `${endDate} 23:59:59`
      }
      getDeliveryApplyList({ ...params }).then(res => {
        const { records, total } = res
        this.total = total
        this.tableData = records
        this.tableDataLoading = false
      }).finally(() => {
        this.tableDataLoading = false
      })
        .finally(() => {
          this.tableDataLoading = false
        })
    },
    initBaseData(type, optionName) {
      this.$store.dispatch('base/getBaseDataList', { type }).then(res => {
        this[optionName] = res
      })
    },
    submitData() {
      this.pageIndex = 1
      this.pageSize = 10
      this.$refs.applicationForm.pageIndex = 1
      this.$refs.applicationForm.pageSize = 10
      this.requestData()
    },
    getLabelForStatus(optionsName, value) {
      const item = this[optionsName].filter(item => `${item.value}` === `${value}`)[0]
      return item ? item.label : '-'
    },
    handlePagination(data) {
      const { pageIndex, pageSize } = data
      this.pageIndex = pageIndex
      this.pageSize = pageSize
      this.requestData()
    },
    toDetail({ id }) {
      this.$router.push({
        name: 'shipDetail',
        params: {
          id
        }
      })
    },
    toCustomerDetail({ companyId }) {
      if (window.__POWERED_BY_QIANKUN__) {
        window.open(`/fina-admin/clientAccountManagement/accountDetail/${companyId}`)
      } else {
        window.open(`/clientAccountManagement/accountDetail/${companyId}`)
      }
    },
    agree(data) {
      this.title = Title.agree
      this.data = data
      this.isAgree = true
      this.visible = true
    },
    reject(data) {
      this.title = Title.reject
      this.data = data
      this.isAgree = false
      this.visible = true
    },
    async handleSubmit(params) {
      this.submitLoading = true
      const fn = this.isAgree ? updateAgree : updateFail
      const message = this.isAgree ? '审批成功！' : '驳回成功！'
      await fn(params).finally(() => {
        this.submitLoading = false
      })
      this.$message({
        message,
        type: 'success'
      })
      this.visible = false
      await this.$store.dispatch('approvalAmount/getAwaitApprovalAmount', { waitApproveUserAccount: this.userAccount })
      this.requestData()
    },
    isCurrentApproval(currentApproveUserList = [], userAccount) {
      const { accountList } = geneateAccountOrNameList(currentApproveUserList)
      return accountList.includes(userAccount)
    }
  }
}
</script>

<style lang="scss" scoped>
  .container {
    margin: 12px;
    width: calc(100% - 24px);
  }
</style>
